package com.xbongbong.paas.service.field;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.saas.enums.NumberTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/04/01 10:06
 */
@Service("numAnalysisHandlerImpl")
public class NumAnalysisHandlerImpl extends AbstractFieldAnalysisHandler {
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;

    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.NUM.getType());
    }

    @Override
    public Object getValue(FieldAttrEntity fieldAttrEntity, PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAnalysisPoJo fieldAnalysisPoJo) throws XbbException {
        // 小数精度
        String key = fieldAttrEntity.getAttr();
        Double value;
        try {
            value = data.getDoubleValue(key);
        } catch (Exception e) {
            value = 0D;
        }
        // 百分比数字字段处理
        String saasAttr = fieldAttrEntity.getSaasAttr();
        boolean rateNumFlag = Objects.equals(ContractEnum.GROSS_PROFIT_RATE.getSaasAttr(), saasAttr)
                || Objects.equals(ContractEnum.CASH_PROFIT_RATE.getSaasAttr(), saasAttr)
                || Objects.equals(ContractEnum.PAY_PERCENT.getSaasAttr(), saasAttr)
                || Objects.equals(SalesOpportunityEnum.GROSS_PROFIT_RATE.getSaasAttr(), saasAttr)
                || Objects.equals(QuotationEnum.GROSS_PROFIT_RATE.getSaasAttr(), saasAttr)
                || Objects.equals(PurchaseEnum.RECEINE_PERCENT.getSaasAttr(), saasAttr);
        if (Objects.equals(fieldAttrEntity.getNumberType(), NumberTypeEnum.RATE.getCode())) {
            rateNumFlag = true;
        }
        if(!rateNumFlag) {
            return  attrDecimalPrecisionHelper.setPrecision(value, fieldAttrEntity.getAccuracy());
        } else {
            String decValue = attrDecimalPrecisionHelper.setDecPrecision(value * 100, fieldAttrEntity.getAccuracy());
            return decValue + "%";
        }
    }
}
